<script setup lang="ts">
import {
  useMessage,
  type TreeOption,
  NForm,
  NFormItem,
  NInput,
  NTreeSelect,
  NInputNumber,
  NSelect,
  type FormInst,
  NButton,
  type FormItemRule
} from 'naive-ui'
import { onMounted, ref, shallowRef } from 'vue'
import type { InstitutionTreeModel, InstitutionModel } from '@/api/sysInstitution'
import type { DicTreeModel } from '@/api/dic'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import { InstitutionDicCode } from '@/enums/system'
import FixedAction from '@/components/FixedAction.vue'
import useGoBack from '@/hooks/useGoBack'

const goBack = useGoBack('/add')

const message = useMessage()

const treeOptions = shallowRef<InstitutionTreeModel[]>([])
const treeLoading = ref(false)
const queryTreeOptions = async () => {
  try {
    treeLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<InstitutionTreeModel[]>>({
      module: 'sysInstitution',
      api: 'getTree'
    })

    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    treeOptions.value = res.data
  } catch (error) {
    console.log(error)
  } finally {
    treeLoading.value = false
  }
}

const typeTreeOptions = shallowRef<DicTreeModel[] | undefined>()
const queryTypeTreeOptions = async () => {
  const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
    module: 'dic',
    api: 'getTree',
    override: {
      params: {
        dicCode: InstitutionDicCode.Parent
      }
    }
  })

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  typeTreeOptions.value = res.data[0]?.children
}

const formInst = shallowRef<FormInst | null>(null)
const formData = ref({} as InstitutionModel)
const submitLoading = ref(false)

const handleSubmit = () => {
  if (submitLoading.value) return
  formInst.value?.validate(async (error) => {
    if (error) return

    try {
      submitLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<InstitutionModel>>({
        module: 'sysInstitution',
        api: 'save',
        override: {
          data: formData.value
        }
      })

      if (error) return message.error(error.message)
      if (res.code !== 0) message.error(res.msg)
      window.flags.flushInstitution = true
      goBack()
    } catch (error) {
      console.log(error)
    } finally {
      submitLoading.value = false
    }
  })
}

const limitTRule: FormItemRule = {
  trigger: ['blur', 'input'],
  validator: (_, value) => {
    return value ? value.length <= 20 : true
  },
  message: '字符长度不能大于20'
}

const limitRule: FormItemRule = {
  trigger: ['blur', 'input'],
  validator: (_, value) => {
    return value ? value.length <= 100 : true
  },
  message: '字符长度不能大于100'
}

onMounted(() => {
  queryTreeOptions()
  queryTypeTreeOptions()
})
</script>

<template>
  <div class="add-institution">
    <NForm
      :disabled="submitLoading"
      :model="formData"
      ref="formInst"
      label-placement="left"
      require-mark-placement="left"
      label-width="100rem"
    >
      <NFormItem
        label="名称："
        path="fullName"
        :rule="[{ required: true, message: '名称为必填项，请输入名称' }, limitTRule]"
      >
        <NInput
          placeholder="请输入"
          v-model:value="formData.fullName"
        />
      </NFormItem>
      <NFormItem
        label="简称："
        path="shortName"
        :rule="limitRule"
      >
        <NInput
          placeholder="请输入"
          v-model:value="formData.shortName"
        />
      </NFormItem>
      <NFormItem
        label="上级部门："
        path="parentId"
        :rule="{
          required: true,
          message: '上级部门为必填项，请选择上级部门',
          type: 'number'
        }"
      >
        <NTreeSelect
          v-model:value="formData.parentId"
          :options="(treeOptions as unknown as TreeOption[])"
          key-field="id"
          default-expand-all
          label-field="name"
          block-line
          placeholder="请选择"
        />
      </NFormItem>
      <NFormItem
        label="部门级别："
        path="insTypeCode"
        :rule="{ required: true, message: '部门级别为必填项，请选择部门级别' }"
      >
        <NTreeSelect
          v-model:value="formData.insTypeCode"
          :options="typeTreeOptions"
          key-field="code"
          default-expand-all
          label-field="name"
          block-line
          placeholder="请选择"
        />
      </NFormItem>
      <NFormItem label="排序：">
        <NInputNumber
          :value="formData.orderIndex"
          @update:value="
                  (e) => (Number.isFinite(e) ? (formData.orderIndex = e as number) : Number.MAX_SAFE_INTEGER)
                "
          style="flex: 1"
          placeholder="请输入"
          :show-button="false"
        />
      </NFormItem>
      <NFormItem
        label="状态："
        path="insStatus"
        :rule="{ required: true, message: '状态为必填项，请选择状态', type: 'number' }"
      >
        <NSelect
          v-model:value="formData.insStatus"
          :options="[
            { label: '启用', value: 1 },
            { label: '禁用', value: 0 }
          ]"
          placeholder="请选择"
        />
      </NFormItem>
      <NFormItem
        label="备注："
        path="notes"
        :rule="limitRule"
      >
        <NInput
          v-model:value="formData.notes"
          type="textarea"
          placeholder="请输入"
        />
      </NFormItem>
      <!-- <span style="padding-left: 100rem">
        带
        <span style="color: #fd4a29">*</span>
        为必填项
      </span> -->
    </NForm>
  </div>

  <FixedAction>
    <div class="add-institution-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="goBack"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.add-institution {
  flex: 1;
  height: 100%;
  padding: 25rem 56rem 0 36rem;

  .n-form {
    min-width: 618rem;
    padding: 25rem 33rem 27rem 20rem;
    background-color: #ebeceb;
  }
}

.add-institution-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
